package com.single.weblearn.typehandler;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.TypeHandler;

@MappedJdbcTypes(JdbcType.BLOB)
public class BlobStringTypeHandler implements TypeHandler<String> {

	@Override
	public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
		byte[] b;
		try {
			b = parameter.getBytes("utf8");
		} catch (UnsupportedEncodingException e) {
			b=parameter.getBytes();
		}
		ByteArrayInputStream bis = new ByteArrayInputStream(b);
		ps.setBinaryStream(i, bis, b.length);		
	}

	@Override
	public String getResult(ResultSet rs, String columnName) throws SQLException {
		Blob blob = rs.getBlob(columnName);
		byte[] b = null;
		if (null != blob) {
			b = blob.getBytes(1, (int) blob.length());
		}
		return byteUtil(b);
	}

	private String byteUtil(byte[] b) {
		
		try {
			return new String(b,"utf8");
		} catch (UnsupportedEncodingException e) {
			return new String(b);
		}
	}

	@Override
	public String getResult(ResultSet rs, int columnIndex) throws SQLException {
		Blob blob = rs.getBlob(columnIndex);
		byte[] returnValue = null;
		if (null != blob) {
			returnValue = blob.getBytes(1, (int) blob.length());
		}
		return byteUtil(returnValue);
	}

	@Override
	public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
		Blob blob = cs.getBlob(columnIndex);
		byte[] returnValue = null;
		if (null != blob) {
			returnValue = blob.getBytes(1, (int) blob.length());
		}
		return byteUtil(returnValue);
	}


}
